package com.jackeysun.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import kotlin.math.abs

/**
 *   Created by sunxunchao on 2021/12/2.
 */
class RoundImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    private var leftTop = 0f
    private var rightTop = 0f
    private var leftBottom = 0f
    private var rightBottom = 0f
    private val path = Path()
    private val radiusArray = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f)

    init {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView)
        leftTop = getAngle(ta.getFloat(R.styleable.RoundImageView_left_top_round, 0f))
        rightTop = getAngle(ta.getFloat(R.styleable.RoundImageView_right_top_round, 0f))
        leftBottom = getAngle(ta.getFloat(R.styleable.RoundImageView_left_bottom_round, 0f))
        rightBottom = getAngle(ta.getFloat(R.styleable.RoundImageView_right_bottom_round, 0f))
        ta.recycle()
        radiusArray[0] = leftTop
        radiusArray[1] = leftTop

        radiusArray[2] = rightTop
        radiusArray[3] = rightTop

        radiusArray[4] = rightBottom
        radiusArray[5] = rightBottom

        radiusArray[6] = leftBottom
        radiusArray[7] = leftBottom


    }

    /**
     * return abs
     */
    private fun getAngle(angle: Float): Float = abs(angle)


    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        //math one
//        path.reset()
//        path.moveTo(leftTop, 0f)
//        path.lineTo(width.toFloat() - rightTop, 0f)
//        path.quadTo(width.toFloat(), 0f, width.toFloat(), rightTop)
//        path.lineTo(width.toFloat(), height.toFloat() - rightBottom)
//        path.quadTo(
//            width.toFloat(),
//            height.toFloat(),
//            width.toFloat() - rightBottom,
//            height.toFloat()
//        )
//        path.lineTo(leftBottom, height.toFloat())
//        path.quadTo(0f, height.toFloat(), 0f, height - leftBottom)
//        path.lineTo(0f, leftTop)
//        path.quadTo(0f, 0f, leftTop, 0f)
//        path.close()
//        canvas?.clipPath(path)
        //math two
        path.reset()
        val rectF = RectF(0f, 0f, width.toFloat(), height.toFloat())
        path.addRoundRect(rectF, radiusArray, Path.Direction.CW) //顺时针
        canvas?.clipPath(path)//剪切
        super.onDraw(canvas)
//        canvas?.drawPath(path, Paint().apply { color = Color.RED })//沿着path绘制
    }

}